import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        userDetails: null,//初始化token
        publicKey: null,
        adminMenus: []
    },
    mutations: {
        initAdminMenu (state, menus) {
            state.adminMenus = menus
        },
        //存储token方法
        //设置token等于外部传递进来的值
        setUserDetails(state, userDetails) {
            state.userDetails = userDetails;
            sessionStorage.setItem("userDetails", userDetails)//同步存储token至sessionStorage
            /*vuex存储在内存，localstorage（本地存储）则以文件的方式存储在本地,永久保存；sessionStorage( 会话存储 ) ,临时保存。localStorage和sessionStorage只能存储字符串类型*/
            // 页面刷新失效
        },
        //存储publicKey方法
        //设置publicKey等于外部传递进来的值
        setPublicKey(state, publicKey) {
            state.publicKey = publicKey;
            sessionStorage.setItem("publicKey", publicKey)//同步存储publicKey至sessionStorage
            /*vuex存储在内存，localstorage（本地存储）则以文件的方式存储在本地,永久保存；sessionStorage( 会话存储 ) ,临时保存。localStorage和sessionStorage只能存储字符串类型*/
            // 页面刷新失效
        },
        //注销清除token方法
        logout(state) {
            state.userDetails = ''
            sessionStorage.removeItem("userDetails")
            state.adminMenus = []
        }
    },
    getters: {
        //获取token方法
        //判断是否有token,如果没有重新赋值，返回给state的token
        getUserDetails: (state) => {
            if (!state.userDetails) {
                state.userDetails = sessionStorage.getItem("userDetails");//若vuex中无token就去sessionStorage中查找
            }
            return state.userDetails;
        },
        //获取publicKey方法
        //判断是否有publicKey,如果没有重新赋值，返回给state的publicKey
        getPublicKey: (state) => {
            if (!state.publicKey) {
                state.publicKey = sessionStorage.getItem("publicKey");//若vuex中无publicKey就去sessionStorage中查找
            }
            return state.publicKey;
        }
    }
})
